package com.siteseat.crudeq.broker.deploy;

import java.io.File;

import com.siteseat.common.deploy.AbstractDeployRepository;
import com.siteseat.common.deploy.DeployEntry;
import com.siteseat.common.exception.InternalException;
import com.siteseat.common.foundation.PropertyHelper;
import com.siteseat.common.security.SecurityException;
import com.siteseat.crudeq.kernel.QueueManager;
import com.siteseat.crudeq.kernel.QueueProfile;

/**
 *
 * @author yqiang
 */
public class QueueDeployRepository extends AbstractDeployRepository {
  
  private Class<QueueProfile> queueProfileClass;
  private QueueManager queueManager;


  /**
   * Gets the queueProfileClass
   *
   * @return the queueProfileClass
   */
  public Class<QueueProfile> getQueueProfileClass() {
    return queueProfileClass;
  }

  /**
   * Sets the queueProfileClass
   *
   * @param queueProfileClass the queueProfileClass to set
   */
  public void setQueueProfileClass( Class<QueueProfile> queueProfileClass ) {
    this.queueProfileClass = queueProfileClass;
  }

  /**
   * Gets the queueManager
   *
   * @return the queueManager
   */
  public QueueManager getQueueManager() {
    return queueManager;
  }

  /**
   * Sets the queueManager
   *
   * @param queueManager the queueManager to set
   */
  public void setQueueManager( QueueManager queueManager ) {
    this.queueManager = queueManager;
  }
  
  /**
   * 
   *
   * @param qf
   */
  public void validateQueueProfile( QueueProfile qf ) {
    try {
      qf.init();
    } catch( Exception e ) {
      throw new InternalException(e);
    }
  }
  
  /**
   * {@inheritDoc}
   */
  @Override
  protected void doDeploy(DeployEntry entry) throws SecurityException {
    File f = entry.getFile();
    QueueProfile q = parseEntityFromJsonFile( f, QueueProfile.class );
    validateQueueProfile( q );
    entry.setData( q );
    
    getQueueManager().deploy( getActorName(), q );
  }


  /**
   * {@inheritDoc}
   */
  @Override
  protected void doUndeploy(DeployEntry entry) throws SecurityException {
    QueueProfile q = (QueueProfile)entry.getData();
    getQueueManager().undeploy( getActorName(), q.getId() );
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected void doInit() throws Exception {
    super.doInit();
    PropertyHelper.ensureNotNull( log, getQueueProfileClass(), "queueProfileClass" );
    PropertyHelper.ensureNotNull( log, getQueueManager(), "queueManager" );    
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected void doDestroy() throws Exception {
    // do nothing so far
  }
  
}
